package org.e_gold.controller;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.e_gold.model.UserAccount;
import org.e_gold.safe.acc.TSAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/home/secret")
public class TSAController {

	private static final Logger log = Logger.getLogger(TSAController.class);

	@Autowired
	private TSAService tsaService;

	@Resource
	private Environment env;

	@RequestMapping(value = "/")
	public ModelAndView mainPage() {

		return new ModelAndView("home");
	}

	@RequestMapping(value = "/index")
	public ModelAndView indexPage() {

		return new ModelAndView("home");
	}
	//http://localhost:7070/e_gold_tsa/home/secret/tsa?amount=0.1
	@RequestMapping(value = "/tsa", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
	public @ResponseBody
	String tsa(@RequestParam("amount") Float amount) {

		try {
			if(amount <= 0.1){
				throw new Exception("Amount must >= 0.1");
			}
			log.info(":: Start transfer : " + amount);
			UserAccount user = new UserAccount();
			user.setUserName(env.getRequiredProperty("txtUsername"));
			user.setPassword(env.getRequiredProperty("txtS3cret"));
			tsaService.transfer(amount, user);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAILED: " + e.getMessage();
		}
		return "SUCCESSED";
	}

}
